import { Router } from 'express'
import { auth, role } from '../middleware/auth.js'
import { Leave } from '../models/Leave.js'
import { loadLeave, ensureCanApprove } from '../middleware/permission.js'

const router = Router()
router.use(auth, role('teacher'))

router.get('/approvals', async (req, res, next) => {
  try {
    const { page = 1, pageSize = 10, status = 'pending' } = req.query

    // 根据状态选择不同的查询逻辑
    let result
    if (status === 'pending') {
      // 待审批：查询所有待审批的申请
      result = await Leave.findAll({
        status: 'pending',
        page: Number(page),
        limit: Math.min(100, Number(pageSize)),
        sortBy: 'created_at',
        order: 'DESC',
      })
    } else if (status === 'all') {
      // 全部：查询该教师已审批过的所有申请（approved 和 rejected）
      result = await Leave.findAllByTeacher({
        teacherId: req.user.id,
        status: null, // null 表示不限制状态
        page: Number(page),
        limit: Math.min(100, Number(pageSize)),
        sortBy: 'updated_at',
        order: 'DESC',
      })
    } else {
      // 已通过/已驳回：查询该教师审批过且为指定状态的申请
      result = await Leave.findAllByTeacher({
        teacherId: req.user.id,
        status: status, // 'approved' 或 'rejected'
        page: Number(page),
        limit: Math.min(100, Number(pageSize)),
        sortBy: 'updated_at',
        order: 'DESC',
      })
    }

    res.json({
      code: 0,
      message: 'ok',
      data: {
        total: result.total,
        page: result.page,
        pageSize: result.limit,
        rows: result.list,
      },
    })
  } catch (error) {
    next(error)
  }
})

router.post('/approvals/:id/approve', loadLeave, ensureCanApprove, async (req, res, next) => {
  try {
    const id = Number(req.params.id)
    const comment = req.body?.comment || '同意'
    const result = await Leave.approve(id, req.user.id, 'approve', comment)

    res.json({ code: 0, message: 'ok', data: result })
  } catch (error) {
    next(error)
  }
})

router.post('/approvals/:id/reject', loadLeave, ensureCanApprove, async (req, res, next) => {
  try {
    const id = Number(req.params.id)
    const comment = req.body?.comment || '不同意'
    const result = await Leave.approve(id, req.user.id, 'reject', comment)

    res.json({ code: 0, message: 'ok', data: result })
  } catch (error) {
    next(error)
  }
})

router.get('/approvals/:id', loadLeave, async (req, res, next) => {
  try {
    res.json({ code: 0, message: 'ok', data: req.leave })
  } catch (error) {
    next(error)
  }
})

router.post('/approvals/:id', loadLeave, ensureCanApprove, async (req, res, next) => {
  try {
    const id = Number(req.params.id)
    const { approved, comment } = req.body || {}

    if (typeof approved !== 'boolean' || !comment)
      return res.status(400).json({ code: 400, message: '参数不完整' })

    // req.leave 已由 loadLeave 加载，ensureCanApprove 已确保状态为 pending 并且角色允许
    const action = approved ? 'approve' : 'reject'
    const result = await Leave.approve(id, req.user.id, action, comment)

    res.json({ code: 0, message: 'ok', data: result })
  } catch (error) {
    next(error)
  }
})

export default router
